/**
 * 
 */
package org.xserver.runtime;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.xserver.Application;
import org.xserver.core.command.CompositeCommand;
import org.xserver.core.command.FolderInitializeCommand;
import org.xserver.core.command.ICommand;
import org.xserver.runtime.jetty.command.ConnectorInitializeCommand;
import org.xserver.runtime.jetty.command.MergeSettingsCommand;
import org.xserver.runtime.jetty.command.ServerStartCommand;
import org.xserver.runtime.jetty.command.ServerStopCommand;
import org.xserver.runtime.jetty.command.SettingsDefaultInitializeCommand;
import org.xserver.runtime.jetty.command.WebAppContextInitializeCommand;
import org.xserver.runtime.jetty.command.WriteSettingsCommand;

/**
 * @author jkonopka
 * 
 */
public final class Main {

	private static final Logger LOG = Logger.getLogger(Main.class);
	private static final Server server = new Server();

	private final Properties properties = new Properties();

	/**
	 * 
	 */
	private Main() {
	}

	/**
	 * @param args commando line arguments
	 */
	public static void main(final String[] args) {
		new Main().run(args);
	}

	/**
	 * @param args
	 */
	private void run(final String[] args) {
		try {

			if (args == null) {
				return;
			}

			getCommand(args).execute();

		} catch (final Exception e) {
			LOG.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * @param args List with Commandoline Argumentes
	 * @return {@link CompositeCommand}
	 */
	private CompositeCommand getCommand(final String[] args) {
		final CompositeCommand command = new CompositeCommand();
		command.add(new FolderInitializeCommand(Application.getUserPath()));
		command.add(new FolderInitializeCommand(Application.getUserConfPath()));
		command.add(new SettingsDefaultInitializeCommand(properties));
		command.add(new MergeSettingsCommand(properties));
		command.add(new WriteSettingsCommand(properties));
		command.add(new ConnectorInitializeCommand(server, properties));
		command.add(new WebAppContextInitializeCommand(server));
		command.add(getServerCommand(args));
		return command;
	}

	/**
	 * @param args
	 * @return command {@link ICommand}
	 */
	private ICommand getServerCommand(final String[] args) {
		if (args.length > 0 && args[0].equals("stop")) {
			return new ServerStopCommand(properties);
		}
		return new ServerStartCommand(server, properties);
	}

}
